﻿// using Microsoft.AspNetCore.Identity;
using EasyDDD.AdminModule.Domain.AggregateSysAdminRole;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace EasyDDD.AdminModule.Application.CommandsSysAdminRole
{
    [AutoMapperTo(typeof(SysAdminRole))]
    public record SysAdminRoleCreateCommand : ICommand<SysAdminRole>
    {
        public string Code { get; set; } = default!;
        public string Name { get; set; } = default!;
        public string Remark { get; set; } = default!;
    }
    public class SysAdminRoleCreateCommandValidator : AbstractValidator<SysAdminRoleCreateCommand>
    {
        public SysAdminRoleCreateCommandValidator(Repository.SysAdminRoleRepository repository)
        {
            var query = repository.AsQueryable();

            RuleFor(x => x.Code).NotEmpty().MaximumLength(10)
                .WithErrorCode("权限标识不能为空");
            RuleFor(x => x.Name).NotEmpty().MaximumLength(10)
                .WithErrorCode("角色名称不能为空");

            RuleFor(x => x.Code).Must((code) => !query.Any(e => e.Code == code))
                .WithMessage("权限标识不能重复");
            RuleFor(x => x.Name).Must((name) => !query.Any(e => e.Name == name))
                .WithMessage("角色名称不能重复");
        }
    }
    public class SysAdminRoleCreateCommandHandler(
       IMapper mapper,
       Repository.SysAdminRoleRepository repository,
       ILogger<SysAdminRoleCreateCommandHandler> logger)
       : ICommandHandler<SysAdminRoleCreateCommand, SysAdminRole>
    {
        public Task<SysAdminRole> Handle(SysAdminRoleCreateCommand request, CancellationToken cancellationToken)
        {
            logger.LogDebug("命令 SysAdminRoleCreateCommandHandler");
            var entity = mapper.Map<SysAdminRole>(request);
            return repository.AddAsync(entity);
        }
    }
}
